"use client";

import { useAuth } from "@/contexts/auth-context";
import { apiFetch, type FetchOptions } from "@/lib/api-client";

export function useApiFetch() {
  const { tokens, refresh, signOut } = useAuth();

  return async function fetchWithAuth<TResponse, TBody = unknown>(options: FetchOptions<TBody>) {
    try {
      return await apiFetch<TResponse, TBody>({
        ...options,
        tokens,
      });
    } catch (error) {
      const status = (error as Error & { status?: number }).status;

      if (status === 401) {
        const refreshed = await refresh();

        if (!refreshed) {
          signOut();
          throw error;
        }

        return apiFetch<TResponse, TBody>({
          ...options,
          tokens: refreshed,
        });
      }

      throw error;
    }
  };
}
